package com.shigen.demo.pattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author shigenfu
 * @date 2024/3/1 17:05
 */
public class ProxyFactory {

    public <T> SmsService getProxyObject(T target) {
        /**
         * ClassLoader loader, 类加载器，加载代理类
         * Class<?>[] interfaces, 真实对象实现接口
         * InvocationHandler h 代理对象处理的函数
         */
        if (target instanceof SmsService) {
            return (SmsService) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                    System.out.println("开始代理");
                    Object result = method.invoke(target, objects);
                    System.out.println("代理结束");
                    return result;
                }
            });
        } else {
            throw new IllegalArgumentException("Target object must implement the specified interface");
        }
    }

}
